<template>
	<div style="padding:0 37px 0 44px">	
	<div class="breadcrumb-father">
      	<div class="new-breadcrumb">
        <router-link  :to="{path:'/welcome'}">
			<img src="../../../assets/imgs/Home.png" alt="">
		</router-link>
		<span>{{$t('newcash.Withdrawal1')}}</span>
		<span class="arrow">></span>
		<span>{{$t('settlement.Settlement')}}</span>
      </div>
    </div>
		<div class="card-table">
			<div class="card-table-title">
				<svg aria-hidden="true" class="svg-icon svg-title-icon"><use xlink:href="#icon-jiaoyiliushui"></use></svg>
				<span>{{$t('settlement.Settlement')}}</span>
			</div>
			<!--搜索输入框-->
			<div class="search">
				<div class="search-input">
          
					<div class="date-wrapper">
						<label for="">{{$t('settlement.Date')}}</label>
						<div class="date-line"></div>
						<el-date-picker :editable=false clearable value-format="yyyy-MM-dd" class="filter-item" type="date" v-model="searchSettlementData.startTime"></el-date-picker>
					</div>

					<div>
						<label for=""></label>
						<el-date-picker :editable=false clearable value-format="yyyy-MM-dd" class="filter-item" type="date" v-model="searchSettlementData.endTime"></el-date-picker>
					</div>

          <div v-if=" userType !== '1' ">
						<label for="">{{ $t('settlement.Merchant') }}</label>
						<el-input v-model="searchSettlementData.merchantName" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
					</div>

					<div v-if=" userType !== '1' ">
						<label for="">{{ $t('settlement.MerchantID') }}</label>
						<el-input v-model="searchSettlementData.merchantNo" clearable :maxlength=14 @keyup.enter.native="handleFilter(0)"></el-input>
					</div>

					<div v-if=" userType !== '1' ">
						<label for="">{{$t('search.AgentName2')}}</label>
            <el-select v-model="searchSettlementData.distributorId" popper-class="el-select-custom" filterable clearable @keyup.enter.native="handleFilter(0)" :placeholder="$t('placeH.All')">
                <el-option v-for="item in queryAgentData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
            </el-select>
					</div>

				    <div class="search-btn-group">
						<el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{$t('button.search')}}</el-button>
						<el-button class="blue-btn mini2-btn" @click='delSelect()'>{{$t('button.Reset')}}</el-button>
					</div>
				</div>
				<!--交易流水表单-->
				<template>
					<div class="table-border">
						<div class="search-result-head">
						<span> {{ searchInfo }} </span>
						<span style="float:right;">
						<a href="javascript:void(0)" @click='export2Excel()' :title="$t('button.SaveResult')"><icon-svg icon-class="daochu"></icon-svg></a> 
						<a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')"><icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg></a>
						</span> 
					</div>
					<!-- 交易流水表 -->
						<el-table border :data="settlementData" height=535 v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
							<el-table-column type="index" fixed :label="$t('index.Number')" width="80"></el-table-column>
							<el-table-column prop="date" :label="$t('settlement.Date')" width=120 :formatter='judgeDate'></el-table-column>
                            <el-table-column prop="merchantName" :label="$t('settlement.Merchant')" width=120 show-overflow-tooltip></el-table-column>
                            <el-table-column prop="merchantNo" :label="$t('settlement.MerchantID')" width=180></el-table-column>
                            <el-table-column prop="settlementDate" :label="$t('settlement.SettlementPeriod')" width=180 :formatter='judgeSettlementDate'></el-table-column>
                            <el-table-column prop="cashier" :label="$t('settlement.TransactionAmount')" width=200 :formatter='judgeCashier'></el-table-column>
                            <el-table-column prop="poundage" :label="$t('settlement.Fee')" :formatter='judgePoundage'></el-table-column>
                            <el-table-column prop="money" :label="$t('settlement.SettlementAmount')" width=200 :formatter='judgemoney'></el-table-column>
                            <el-table-column v-if="companyId == 1" prop="endamt" :label="$t('mer.AvailableBalance')" width=200 :formatter='judgeendamt'></el-table-column>
                            <el-table-column v-if="companyId == 1" prop="balance" :label="$t('mer.AccountBalance')" width=200 :formatter='judgebalance'></el-table-column>
						</el-table>
					</div>
				</template>
			</div>
		</div>
  		
  		<div class="pagination-container">
    		<el-pagination :total="res.total" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="searchSettlementData.page" :page-sizes="[15,20,30, 50]" :page-size="searchSettlementData.pageSize" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
  		</div>
	</div>
</template>

<script>
import { loadPage } from 'api/settlement/index';
import { searchDistributor } from "api/businessManagement/merchant/index";
import XLSX from "xlsx";
import XLSX_SAVE from "file-saver";

export default {
  name: "Settlement",
  data() {
    return {
      res: [],
      companyId:localStorage.getItem('companyId'),
      distributorId:localStorage.getItem('distributorId'),
      userType:localStorage.getItem('userType'),
      grade:localStorage.getItem('grade'),
      firmId:localStorage.getItem('firmId'),
      salesmanId:localStorage.getItem('salesmanId'),
      merchantId:localStorage.getItem('merchantId'),
      searchSettlementData: {
        merchantName:undefined,
        merchantNo:undefined,
        distributorId:undefined,
        startTime:undefined,
        endTime:undefined,
        page: 1,
        pageSize: 15
      },
      queryAgentData: [],
      settlementData: [],
      searchInfo: "",
      rorateFlag: true,
      currency:'',
      degIndex:1,
      oldPage: null,
      loading: true,
    };
  },
  watch:{
    'searchSettlementData.page':function(newVal,oldVal){
        this.oldPage = oldVal;
    },
  },
  created() {
    if (this.companyId == '1') this.currency = 'HK$ ';
    if (this.companyId == '2') this.currency = 'A$ ';

    this.searchInfo = this.$t('settlement.Settlement');
    this.searchDistributor();

    this.getSettlementData(this.searchSettlementData);
  },
  methods: {
    // 获得代理商下拉框的数据
    searchDistributor() {
      let searchData = {};
      
      if(this.userType == 2 && this.grade > 0) {
        searchData.distributorId = this.distributorId;
      }else if(this.userType == 5 || this.userType == 9 || this.grade == 0 || this.userType == 0 || this.userType == 11 ) {
        searchData.companyId = this.companyId;  
      }else if(this.userType == 10) {
        searchData.firmId = this.firmId;
      }else if(this.userType == 8) {
        searchData.salesmanId = this.salesmanId;
      }else if(this.userType == 1) {
        searchData.merchantId = this.merchantId;
      }

      searchDistributor(searchData).then(res => {
          if (res.code == 0) {
            // console.log("查询所属代理商返回数据：" + res);
            this.queryAgentData = res.value;
          }
        })
        .catch(() => {});
    },
    // 格式化时间
    judgeDate(row){
        let date = row.date;
        return date.substring(0,10);
    },
    //格式化结算周期
    judgeSettlementDate(row){
      let formatDate = row.settlementDate;
      if( row.settlementDate ){
        return formatDate = "T+" + formatDate;
      } else {
         return;
      }
      
    },
    // 格式化金额
    judgemoney(row){
      let formatMoney = row.money;
      if( row.money ){
        return formatMoney = this.currency + this.fmoney(formatMoney, 2);
      }else{
        return formatMoney = this.currency + '0.00';
      } 
    },
    judgeCashier(row){
      let formatCashier = row.cashier;
      if(row.cashier){
        return formatCashier = this.currency + this.fmoney(formatCashier, 2);
      }else{
        return formatCashier = this.currency + '0.00';
      } 
    },
    judgePoundage(row){
      let formatPoundage = row.poundage;
      if( row.poundage ){
        return formatPoundage = this.currency + this.fmoney(formatPoundage, 2);
      }else{
        return formatPoundage = this.currency + '0.00';
      } 
    },
    judgebalance(row){
        let formatBalance = row.balance;
      if( row.balance ){
        return formatBalance = this.currency + this.fmoney(formatBalance, 2);
      }else{
        return formatBalance = this.currency + '0.00';
      } 
    },
    judgeendamt(row){
        let formatEndamt = row.endamt;
      if( row.money ){
        return formatEndamt = this.currency + this.fmoney(formatEndamt, 2);
      }else{
        return formatEndamt = this.currency + '0.00';
      } 
    },
    // 查询商户结算数据
    getSettlementData(data,str){
    let listQuery = {};
		$.extend(listQuery, data);
        listQuery.companyId = this.companyId;
        if( this.userType == '1' ) listQuery.merchantId = this.merchantId;
        if( this.userType == '2' && !listQuery.distributorId && this.grade > 0 ) listQuery.distributorId = this.distributorId;
        if( this.userType == '8' ) listQuery.salesmanId = this.salesmanId;
        if( this.userType == '10' ) listQuery.firmId = this.firmId;
        loadPage(listQuery).then(res=>{
            const _that = this;
            this.res = res.value;
            this.settlementData = res.value.list;

            // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
            if( str == 'CurrentChange' ){
              let obj = $('.el-pager .number');
              for( let i = 0; i < obj.length; i++){
                  if($(obj[i]).html() == this.searchSettlementData.page) {
                    $(obj[i]).addClass('active');
                  } else {
                    $(obj[i]).removeClass('active');
                  }
              }
            }

            setTimeout(function() {
              // 隐藏载入提示层
              _that.loading = false;
            },500)

        })
    },
    //点击搜索 查询订单
    handleFilter(sign,str) { 

      // 显示载入提示层
      this.loading = true;

      // sign 0 搜索 1其他
      if (sign === 0) this.searchInfo = this.$t("index.searchResults");
      //查询商户结算的参数
      this.exportSearchData = {};
      $.extend(this.exportSearchData, this.searchSettlementData);
      this.formatObj(this.exportSearchData);
      // console.log("设备查询向后台发送的数据");
      // console.log(searchSettlementData);
      this.getSettlementData(this.exportSearchData,str);

      if( str == 'CurrentChange' ){
        // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
        let obj = $('.el-pager .number');
        for( let i = 0; i < obj.length; i++){
            if($(obj[i]).html() == this.oldPage) {
              console.log(this.oldPage);
              $(obj[i]).addClass('active');
            } else {
              $(obj[i]).removeClass('active');
            }
        }
      }

    },
    // 清空筛选条件
    delSelect() {
      this.searchSettlementData.merchantName = null;
      this.searchSettlementData.merchantNo = null;
      this.searchSettlementData.distributorId = null;
      this.searchSettlementData.startTime = null;
      this.searchSettlementData.endTime = null;
      this.searchSettlementData.page = 1;
      this.searchSettlementData.pageSize = 15;
      this.searchInfo = this.$t("settlement.Settlement");
      this.handleFilter(1);
    },
    //刷新数据
    refresh() {
      const _that = this;
      if (this.rorateFlag) {
        document.getElementById("refresh_icon").style.transform = "rotate(" + this.degIndex * 360 + "deg)";
        this.handleFilter(1);
        this.rorateFlag = false;
        setTimeout(function(param) {
          _that.rorateFlag = true;
          _that.degIndex++;
        }, 1000);
      }
	},
	    //pageSize 改变时会触发
    handleSizeChange(val) {
      this.searchSettlementData.pageSize = val;
      this.handleFilter(1);
    },
    //currentPage 改变时会触发
    handleCurrentChange(val) {
      this.searchSettlementData.page = val;
      this.handleFilter(1);
    },
    //导出表格
    export2Excel() {
      let length = this.res.total;
      require.ensure([], () => {
        let listQuery = {};
        $.extend(listQuery, this.exportSearchData);
        listQuery.pageSize = length;
        listQuery.page = 1;
        listQuery.companyId = localStorage.getItem('companyId');
        if( this.userType == '1' ) listQuery.merchantId = this.merchantId;
        if( this.userType == '2' && !listQuery.distributorId && this.grade > 0 ) listQuery.distributorId = this.distributorId;
        if( this.userType == '8' ) listQuery.salesmanId = this.salesmanId;
        if( this.userType == '10' ) listQuery.firmId = this.firmId;
        loadPage(listQuery).then(res => {
          const list = res.value.list;
          const { export_json_to_excel } = require("../../../vendor/Export2Excel");
          //对应表格输出的title
          let tHeader = [
            this.$t('settlement.Date'),
            this.$t("settlement.Merchant"),
            this.$t('settlement.MerchantID'),
            this.$t('settlement.SettlementPeriod'),
            this.$t('settlement.TransactionAmount')+' '+ this.currency,
            this.$t('settlement.Fee')+' '+ this.currency,
            this.$t('settlement.SettlementAmount')+' '+ this.currency,
          ];
          // 对应表格输出的数据
          let filterVal = [
            "date",
            "merchantName",
            "merchantNo",
            "settlementDate",
            "cashier",
            "poundage",
            "money",
          ];

          if ( this.companyId == 1 ){
            tHeader.splice(7,0,this.$t('mer.AvailableBalance')+' '+ this.currency,this.$t('mer.AccountBalance')+' '+ this.currency);
            filterVal.splice(7,0,"endamt","balance");
          }

          for (let i = 0; i < list.length; i++) {
            if(list[i].settlementDate){
              list[i].settlementDate = 'T+' + list[i].settlementDate;
            }

            if(list[i].money) {
              list[i].money = list[i].money / 100;
            }

            if(list[i].poundage) {
              list[i].poundage = list[i].poundage / 100;  
            }else {
              list[i].poundage = '0.00';
            }

            if(list[i].cashier) {
              list[i].cashier = list[i].cashier / 100;
            }else {
              list[i].cashier = '0.00';
            }

            if(list[i].endamt) {
              list[i].endamt = list[i].endamt / 100;
            }else {
              list[i].endamt = '0.00';
            }

            if(list[i].balance) {
              list[i].balance = list[i].balance / 100;
            }else {
              list[i].balance = '0.00';
            }
            list[i].date = list[i].date.substring(0,10);

          }
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, this.$t("settlement.Settlement")); //对应下载文件的名字
        });
      });
    },
    // 格式化金额
    fmoney(s, n) {
      if( s === "" || s === undefined ) return s = "0.00";
      s = s / 100;
      n = n > 0 && n <= 20 ? n : 2;
      s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
      var l = s
          .split(".")[0]
          .split("")
          .reverse(),
        r = s.split(".")[1];
      let t = "";
      for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
      }
      return (
        t
          .split("")
          .reverse()
          .join("") +
          "." +
           r
      );
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    formatObj(obj) {
      let arr = Object.keys(obj);
      for (let i = 0; i < arr.length; i++) {
        if (obj[arr[i]] === "") {
          obj[arr[i]] = null;
        }
      }
    }
  }
};
</script>

<style scoped>
</style>